package com.haust.service.impl;

import com.haust.commons.pojo.HaustResult;
import com.haust.service.FileUpLoadService;
import com.haust.utils.FastDFSClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

@Service
public class FileUpLoadServiceImpl implements FileUpLoadService {
    @Value("${Haust.fastdfs.nginx}")
    private String nginxServer;


    @Override
    public HaustResult upload(MultipartFile multipartFile) {
        InputStream inputStream = null;
        String originalFilename = null;
        try {
            inputStream = multipartFile.getInputStream();
            originalFilename = multipartFile.getOriginalFilename();
            String[] result = FastDFSClient.uploadFile(inputStream, originalFilename);

            if (result == null) {
                return HaustResult.error("FastDfS上传错误。服务繁忙，请稍后再试");
            }
            String url = nginxServer + result[0] + "/" + result[1];
            return HaustResult.ok(url);

        } catch (IOException e) {
            e.printStackTrace();
            return HaustResult.error("获取输入流失败。服务繁忙，请稍后再试");
        }
    }
}
